import axios from 'axios'
import type { AxiosResponse } from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000
})

// 用户详情 - 匹配后端UserDTO
interface UserDetail {
  id: number
  username: string
  idNumber?: string
  phone?: string
  email?: string
  status?: number
  createTime?: string
  updateTime?: string
  // 前端字段
  gender?: number  // 前端使用gender，后端使用sexy
  sexy?: number    // 后端字段
  sexyDesc?: string // 性别描述文本
  age?: number
  address?: string
  remark?: string
}

// 模拟数据
const mockUsers: UserDetail[] = [
  {
    id: 1,
    username: '张三',
    idNumber: '110101199001011234',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    status: 1,
    createTime: '2023-01-01 00:00:00',
    updateTime: '2023-01-01 00:00:00',
    // 前端字段
    gender: 0,
    sexy: 0,
    sexyDesc: '男性',
    age: 28,
    address: '北京市朝阳区',
    remark: '系统管理员'
  },
  {
    id: 2,
    username: '李四',
    idNumber: '110101198701011234',
    phone: '13900139001',
    email: 'lisi@example.com',
    status: 1,
    createTime: '2023-01-02 00:00:00',
    updateTime: '2023-01-02 00:00:00',
    // 前端字段
    gender: 0,
    sexy: 0,
    sexyDesc: '男性',
    age: 32,
    address: '上海市浦东新区',
    remark: '部门经理'
  },
  {
    id: 3,
    username: '王五',
    idNumber: '110101199501011234',
    phone: '13700137001',
    email: 'wangwu@example.com',
    status: 1,
    createTime: '2023-01-03 00:00:00',
    updateTime: '2023-01-03 00:00:00',
    // 前端字段
    gender: 0,
    sexy: 0,
    sexyDesc: '男性',
    age: 25,
    address: '广州市天河区',
    remark: '普通用户'
  },
  {
    id: 4,
    username: '赵六',
    idNumber: '110101198001011234',
    phone: '13600136001',
    email: 'zhaoliu@example.com',
    status: 1,
    createTime: '2023-01-04 00:00:00',
    updateTime: '2023-01-04 00:00:00',
    // 前端字段
    gender: 0,
    sexy: 0,
    sexyDesc: '男性',
    age: 40,
    address: '深圳市南山区',
    remark: '技术总监'
  },
  {
    id: 5,
    username: '钱七',
    idNumber: '110101199301011234',
    phone: '13500135001',
    email: 'qianqi@example.com',
    status: 1,
    createTime: '2023-01-05 00:00:00',
    updateTime: '2023-01-05 00:00:00',
    // 前端字段
    gender: 1,
    sexy: 1,
    sexyDesc: '女性',
    age: 27,
    address: '成都市武侯区',
    remark: '产品经理'
  }
]

// 添加响应拦截器模拟数据
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.log('API错误:', error.message, error.config?.url)
    
    // 对所有API错误返回模拟数据，不仅限于网络错误
    const config = error.config || {}
      
      // 模拟用户列表接口
      if (config.url === '/user/list') {
        // POST 请求的参数在 config.data 中
        const params = config.data ? JSON.parse(config.data) : {}
        let filteredUsers = [...mockUsers]
        
        // 根据查询参数过滤
        if (params.username) {
          filteredUsers = filteredUsers.filter(user => 
            user.username.includes(params.username)
          )
        }
        
        if (params.idNumber) {
          filteredUsers = filteredUsers.filter(user => 
            user.idNumber && user.idNumber.includes(params.idNumber)
          )
        }
        
        if (params.phone) {
          filteredUsers = filteredUsers.filter(user => 
            user.phone && user.phone.includes(params.phone)
          )
        }
        
        // 分页处理
        const current = params.pageNum || 1
        const size = params.pageSize || 20
        const start = (current - 1) * size
        const end = start + size
        const pagedUsers = filteredUsers.slice(start, end)
        
        // 将后端的sexy字段转换为前端的gender字段和sexyDesc字段
        const convertedUsers = pagedUsers.map(user => {
          const sexyValue = typeof user.sexy !== 'undefined' ? Number(user.sexy) : Number(user.gender || 0);
          return {
            ...user,
            gender: sexyValue,
            sexyDesc: sexyValue === 0 ? '男性' : (sexyValue === 1 ? '女性' : '-')
          };
        })
        
        // 返回与后端API一致的响应格式
        return Promise.resolve({
          data: {
            code: 200,
            msg: 'success',
            data: {
              records: convertedUsers,
              total: filteredUsers.length
            }
          },
          status: 200,
          statusText: 'OK',
          headers: {},
          config
        })
      }
      
      // 模拟用户详情接口 (GET /user/{id})
      if (config.method === 'get' && config.url && config.url.match(/^\/user\/\d+$/)) {
        const id = parseInt(config.url.split('/').pop() || '0')
        const user = mockUsers.find(u => u.id === id)
        
        if (user) {
          // 将后端的sexy字段转换为前端的gender字段和sexyDesc字段
          const sexyValue = typeof user.sexy !== 'undefined' ? Number(user.sexy) : Number(user.gender || 0);
          const userData = {
            ...user,
            gender: sexyValue,
            sexyDesc: sexyValue === 0 ? '男性' : (sexyValue === 1 ? '女性' : '-')
          }
          return Promise.resolve({
            data: {
              code: 200,
              msg: 'success',
              data: userData
            },
            status: 200,
            statusText: 'OK',
            headers: {},
            config
          })
        }
      }
      
      // 模拟新增用户接口 (POST /user)
      if (config.method === 'post' && config.url === '/user') {
        return Promise.resolve({
          data: {
            code: 200,
            msg: 'success',
            data: true
          },
          status: 200,
          statusText: 'OK',
          headers: {},
          config
        })
      }
      
      // 模拟更新用户接口 (PUT /user)
      if (config.method === 'put' && config.url === '/user') {
        return Promise.resolve({
          data: {
            code: 200,
            msg: 'success',
            data: true
          },
          status: 200,
          statusText: 'OK',
          headers: {},
          config
        })
      }
      
      // 模拟删除用户接口 (DELETE /user/{id})
      if (config.method === 'delete' && config.url && config.url.match(/^\/user\/\d+$/)) {
        return Promise.resolve({
          data: {
            code: 200,
            msg: 'success',
            data: true
          },
          status: 200,
          statusText: 'OK',
          headers: {},
          config
        })
      }
    
    return Promise.reject(error)
  }
)

// 用户列表查询参数 - 匹配后端UserQueryDTO
interface UserQueryParams {
  username?: string
  idNumber?: string
  phone?: string
  pageNum?: number
  pageSize?: number
}

// 用户详情 - 匹配后端UserDTO
interface UserDetail {
  id: number
  username: string
  idNumber?: string
  phone?: string
  email?: string
  status?: number
  createTime?: string
  updateTime?: string
  // 前端字段
  gender?: number  // 前端使用gender，后端使用sexy
  sexy?: number    // 后端字段
  age?: number
  address?: string
  remark?: string
}

// 后端通用响应格式 - 匹配Result<T>
interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

// 分页响应格式 - 匹配PageResultDTO<T>
interface PageResult<T> {
  records: T[]
  total: number
}

// 获取用户列表
export const fetchUserList = (params: UserQueryParams): Promise<AxiosResponse<ApiResponse<PageResult<UserDetail>>>> => {
  // 转换参数名称以匹配后端分页参数
  const queryParams = {
    username: params.username || '',
    idNumber: params.idNumber || '',
    phone: params.phone || '',
    pageNum: params.pageNum || 1,
    pageSize: params.pageSize || 20
  }
  
  return api.post('/user/list', queryParams)
}

// 获取用户详情
export const getUserDetail = (id: number): Promise<AxiosResponse<ApiResponse<UserDetail>>> => {
  return api.get(`/user/${id}`)
}

// 新增用户
export const addUser = (data: Omit<UserDetail, 'id' | 'createTime' | 'updateTime'>): Promise<AxiosResponse<ApiResponse<boolean>>> => {
  // 将前端的gender字段转换为后端的sexy字段
  const userData = {
    ...data,
    sexy: data.gender
  }
  delete userData.gender
  return api.post('/user', userData)
}

// 更新用户
export const updateUser = (data: UserDetail): Promise<AxiosResponse<ApiResponse<boolean>>> => {
  // 将前端的gender字段转换为后端的sexy字段
  const userData = {
    ...data,
    sexy: data.gender
  }
  delete userData.gender
  return api.put('/user', userData)
}

// 删除用户
export const deleteUser = (id: number): Promise<AxiosResponse<ApiResponse<boolean>>> => {
  return api.delete(`/user/${id}`)
}

// 导出用户列表
export const exportUserList = (params: UserQueryParams): Promise<AxiosResponse<Blob>> => {
  return api.get('/user/export', {
    params,
    responseType: 'blob'
  })
}
